/*-------------------------工具类---------------------------------------------*/

/*
	获取页面传递参数
*/
UrlParm = function() { // url参数
	var data, index;
	(function init() {
		data = [];
		index = {};
		var u = window.location.search.substr(1);
		if (u != '') {
			var parms = decodeURIComponent(u).split('&');
			for (var i = 0, len = parms.length; i < len; i++) {
				if (parms[i] != '') {
					var p = parms[i].split("=");
					if (p.length == 1 || (p.length == 2 && p[1] == '')) {
						data.push(['']);
						index[p[0]] = data.length - 1;
					} else if (typeof(p[0]) == 'undefined' || p[0] == '') {
						data[0] = [p[1]];
					} else if (typeof(index[p[0]]) == 'undefined') { // c=aaa
						data.push([p[1]]);
						index[p[0]] = data.length - 1;
					} else { // c=aaa
						data[index[p[0]]].push(p[1]);
					};
				};
			};
		};
	})();
	return {
		// 获得参数,类似request.getParameter()
		parm: function(o) { // o: 参数名或者参数次序
			try {
				return (typeof(o) == 'number' ? data[o][0] : data[index[o]][0]);
			} catch (e) {}
		},
		//获得参数组, 类似request.getParameterValues()
		parmValues: function(o) { //  o: 参数名或者参数次序
			try {
				return (typeof(o) == 'number' ? data[o] : data[index[o]]);
			} catch (e) {}
		},
		//是否含有parmName参数
		hasParm: function(parmName) {
			return typeof(parmName) == 'string' ? typeof(index[parmName]) != 'undefined' : false;
		},
		// 获得参数Map ,类似request.getParameterMap()
		parmMap: function() {
			var map = {};
			try {
				for (var p in index) {
					map[p] = data[index[p]];
				}
			} catch (e) {}
			return map;
		}
	};
}();

/**
 * 显示加载动画
 */
function showload(type){
	if($('#dh-bd').length == 0){
		let demo = "";
		if(type == 1){
			demo = "<div class='demo1'>"
				 + "	<img src='img/ing.png'/>"
				 + "	<div>加载中</div>"
				 + "</div>";
		}
		let html = "<div id='dh-bd'>"+demo+"</div>";
		$('body').append(html);
	}
};

/**
 * 移除加载动画
 */
function hideload(){
	if($('#dh-bd').length != 0){
		$('#dh-bd').remove();
	}
};
/*
	接口请求1
*/
function postF(url, data, type, sucF, errF) {
	if (url != '') {
		var postload = null;
		url = ym + url;
		console.log(url + '接口请求');
		console.log(url + '接口请求,参数:' + data);
		$.ajax({
			async: false, //同步，异步
			type: type, //请求类型"post",
			url: url, //请求的服务端地址
			contentType: 'application/json', //请求方式
			data: JSON.stringify(data), //请求参数
			dataType: "json",
			beforeSend: function() {
				//显示加载动画
				showload(1)
			},
			success: function(res) {
				if (res.result.code == '2001') {
					//清除用户缓存
					remove_cache('userInfo');
					layer.msg('用户信息不存在,请重新访问链接', {
						time: 2000
					});
					return;
				};
				console.log(url + '接口请求,回调', res);
				if (sucF) {
					sucF(res);
				}
			},
			error: function(err) {
				console.log('接口请求出错' + err)
				if (errF) {
					errF(err);
				}
			},
			complete: function() {
				//移除加载动画
				hideload()
			}
		});
	};
};

/*
	接口请求2
*/
function postF2(url, data, type, dataType, contentType, sucF, errF) {
	if (url != '') {
		var postload = null;
		url = ym + url;
		console.log(url + '接口请求');
		console.log(url + '接口请求,参数:' + JSON.stringify(data));
		$.ajax({
			async: false, //同步，异步
			type: type, //请求类型"post",
			url: url, //请求的服务端地址
			contentType: contentType ? contentType : 'application/json', //请求方式
			data: contentType != 'application/x-www-form-urlencoded' ? JSON.stringify(data) : data, //请求参数
			dataType: dataType ? dataType : "json",
			beforeSend: function() {
				//显示加载动画
				showload(1)
			},
			success: function(res) {
				if (res.result.code == '2001') {
					//清除用户缓存
					remove_cache('userInfo');
					layer.msg('用户信息不存在,请重新访问链接', {
						time: 2000
					});
					return;
				};
				//授权成功清除登录请求次数
				if (url.indexOf(jkMap.authorize) != -1) {
					remove_cache('wxlognnum');
				};
				console.log(url + '接口请求,回调', res);
				if (sucF) {
					sucF(res);
				}
			},
			error: function(err) {
				console.log('接口请求出错' + err)
				if (errF) {
					errF(err);
				}
			},
			complete: function() {
				//移除加载动画
				hideload()
			}
		});
	};
};

/**
 * @param {Object} userId 用户id
 */
function sxUserInfo(userId, sucF, errF) {
	postF(jkMap.getuserinfo + '?userId=' + userId, undefined, 'get', sucF, errF);
};

/*
	设置缓存
*/
function set_cache(key, value) {
	if (key == '') return false;
	localStorage.setItem(key, JSON.stringify(value));
};

/*
	读取缓存
*/
function get_cache(key) {
	return JSON.parse(localStorage.getItem(key));
};
/*
	删除缓存
*/
function remove_cache(key) {
	localStorage.removeItem(key);
};

/*
	写入cookie
*/
function setCookie(name, value) {
	var Days = 30;
	var exp = new Date();
	exp.setTime(exp.getTime() + Days2460601000);
	document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
};

/*
	获取cookie
*/
function getCookie(name) {
	var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
	if (arr = document.cookie.match(reg))
		return unescape(arr[2]);
	else
		return null;
};

/*
	删除cookie
*/
function delCookie(name) {
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var cval = getCookie(name);
	if (cval != null)
		document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
};

function copyText(event) {
	var flg = false;
	if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {
		const range = document.createRange();
		range.selectNode(document.getElementById('data_weChat'));
		const selection = window.getSelection();
		if (selection.rangeCount > 0) selection.removeAllRanges();
		selection.addRange(range);
		document.execCommand('copy');
		flg = true;
	} else {
		var input = document.createElement('input');
		input.setAttribute('readonly', 'readonly');
		input.setAttribute('value', event);
		document.body.appendChild(input);
		input.setSelectionRange(0, 9999);
		input.select();
		if (document.execCommand('copy')) {
			document.execCommand('copy');
		};
		document.body.removeChild(input);
		flg = true;
	};
	return flg;
};

/**--------------------------------------公共接口-------------------------------------------------------**/
/**
 * 用户是否关注采集
 */
function focusCJ(userId, sucF, errF) {
	postF(jkMap.userpublic + '?userId=' + userId, undefined, 'get', function(res) {
		sucF(res);
	}, errF);
};

/**
 * 查看文案详情
 * @param {Object} articleid 文案id
 */
function getArticleDetail(articleid, sucF, errF) {
	postF(jkMap.articleinfo + '/' + articleid, undefined, 'get', sucF, errF);
};

/**
 * 查看名片信息
 * @param {Object} userId 用户ID
 */
function getCardInfo(userId, sucF, errF) {
	postF(jkMap.cardinfo + '/' + userId, undefined, 'get', sucF, errF);
};

/**
 * 微信js-apinfig注入参数获取
 * @param {Object} url
 * @param {Object} sucF
 * @param {Object} errF
 */
function jsconfig(url, sucF, errF) {
	// url = encodeURIComponent(url);
	// postF2(jkMap.jsconfig + '?url=' + url, undefined, 'get', 'json', 'application/x-www-form-urlencoded', sucF, errF);
	postF(jkMap.jsconfig, {
		url: url
	}, 'post', sucF, errF);
};

/**
 * 微信网页授权跳转
 * @param {Object} url
 * @param {Object} state
 */
function wxlogn(url, data) {
	if (url) {
		url = encodeURIComponent(url);
		if (data && data != '' && data != 'undefined') {
			var data = encodeURIComponent(encodeURIComponent(data));
			url = url + '?params=' + data;
		};

		window.location.href =
			'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + pappId +
			'&connect_redirect=1&redirect_uri=' + url + '&response_type=code&scope=snsapi_userinfo#wechat_redirect';
	};
};

/*-----------------------------------工具函数----------------------------------------------------*/
/**
 * 判断设备 0-未知 1-ios 2-安卓
 */
function isIosOrAn() {
	var type = 0; //0-未知 1-ios 2-安卓
	var u = navigator.userAgent,
		app = navigator.appVersion;
	var browser = {
		versions: function() {
			return { //移动终端浏览器版本信息
				trident: u.indexOf('Trident') > -1, //IE内核
				presto: u.indexOf('Presto') > -1, //opera内核
				webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
				gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
				mobile: !!u.match(/AppleWebKit.*Mobile/i) || !!u.match(
					/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/
				), //是否为移动终端
				ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
				android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
				iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
				iPad: u.indexOf('iPad') > -1, //是否iPad
				webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
			};
		}(),
		language: (navigator.browserLanguage || navigator.language).toLowerCase()
	};
	if (browser.versions.iPhone || browser.versions.iPad || browser.versions.ios) {
		type = 1;
	} else if (browser.versions.android) {
		type = 2;
	};
	return type;
};

/**
 * 判断是否微信浏览器
 */
function isWeiXin() {
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true;
	} else {
		return false;
	};
};

/*
 ** 时间戳转换成指定格式日期
 ** eg. 
 ** dateFormat(11111111111111, 'Y年m月d日 H时i分')
 ** → "2322年02月06日 03时45分"
 */
function dateFormat(timestamp, formats) {
	// formats格式包括
	// 1. Y-m-d
	// 2. Y-m-d H:i:s
	// 3. Y年m月d日
	// 4. Y年m月d日 H时i分
	formats = formats || 'Y-m-d';

	var zero = function(value) {
		if (value < 10) {
			return '0' + value;
		};
		return value;
	};

	var myDate = timestamp ? new Date(timestamp) : new Date();

	var year = myDate.getFullYear();
	var month = zero(myDate.getMonth() + 1);
	var day = zero(myDate.getDate());

	var hour = zero(myDate.getHours());
	var minite = zero(myDate.getMinutes());
	var second = zero(myDate.getSeconds());

	return formats.replace(/Y|m|d|H|i|s/ig, function(matches) {
		return ({
			Y: year,
			m: month,
			d: day,
			H: hour,
			i: minite,
			s: second
		})[matches];
	});
};

/**
 * 关注二维码弹窗
 */
function focusDivTc() {
	if ($('#gzgzh').length == 0) {
		var html = '<div id="gzgzh">' +
			'		<img src="img/gzh.jpg" />' +
			'		<div>长按图片识别关注公众号</div>' +
			'		<div>（ 关注成功后请刷新页面 ）</div>' +
			'	</div>';
		$('body').append(html);
		$('#gzgzh').click(function() {
			$(this).hide();
		});
	} else {
		$('#gzgzh').show();
	};
};
